package com.example.kafka.utils;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.TopicDescription;

import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class KafkaPartitionInfo {

    /**
     * kafka客户端监控：可查看某个topic下面的分区信息
     * @author wanghongyu02
     * @date 2024-07-26 11:37
     * @param args
     * @return
     */
    public static void main(String[] args) {
        Properties config = new Properties();
        config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        AdminClient adminClient = AdminClient.create(config);

        try {
            Map<String, TopicDescription> topics = adminClient.describeTopics(Collections.singletonList("mytopic1")).all().get();
            TopicDescription topicDescription = topics.get("mytopic1");

            System.out.println("Partitions for topic 'mytopic1':");
            topicDescription.partitions().forEach(partitionInfo -> {
                System.out.println("Partition ID: " + partitionInfo.partition());
                System.out.println("Leader: " + partitionInfo.leader());
                System.out.println("Replicas: " + partitionInfo.replicas());
                System.out.println("ISR: " + partitionInfo.isr());
                System.out.println();
            });
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            adminClient.close();
        }
    }
}